import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { AMapKey, getCityInfo } from "../../utils/index";
import NavHeader from "../../components/NavHeader";
import "./index.less";

const cityInfo = getCityInfo("HKZF_CITY");

const url = "http://192.168.9.228:9999";

const mapLabelStyle = {
  borderRadius: "1rem",
  backgroundColor: "#02a16b",
  color: "#fff",
  width: "2rem",
  height: "2rem",
  textAlign: "center",
  lineHeight: "2rem",
  fontSize: "20px",
  opacity: "0.8",
};

export default function Map() {
  const navigate = useNavigate();

  useEffect(() => {
    initMap();
  }, []);

  // 创建地图实例
  async function initMap() {
    try {
      const AMap = await AMapKey;

      const map = new AMap.Map("container", { zoom: 10, isHotspot: true });

      // 获取区数据
      const { data } = await axios.get(url + `/area/map?id=${cityInfo.value}`);
      // 圆圈标识
      const textLabel = [];

      if (data.status === 200 && data.description === "请求成功") {
        const list = data.body;
        list.length &&
          list.forEach((item) => {
            let areaPoint = new AMap.LngLat(item.coord.longitude, item.coord.latitude);
            let res = new AMap.Text({
              anchor: "center",
              cursor: "pointer",
              position: areaPoint,
              id: item.value,
            });
            res.setContent(`
              <div class="bubble">
                <p class="name">${item.label}</p>
                <p class="count">${item.count}套</p>
              </div>
            `);
            res.setStyle(mapLabelStyle);
            res.on("click", () => {
              // 放大地图
              map.setZoomAndCenter(13, areaPoint);
              // 清除当前覆盖物信息
              map.clearMap();
            });
            textLabel.push(res);
          });
      }

      AMap.plugin(["AMap.Geocoder", "AMap.ToolBar", "AMap.Scale"], () => {
        let geocoder = new AMap.Geocoder({ city: "全国" });

        // 比例尺
        var scale = new AMap.Scale();
        map.addControl(scale);
        //加载工具条
        let tool = new AMap.ToolBar();
        map.addControl(tool);

        geocoder.getLocation(cityInfo.label, (status, result) => {
          if (status === "complete" && result.geocodes.length) {
            let lnglat = result.geocodes[0].location;
            map.setCenter(lnglat);
            map.setZoom(10);
            map.add(textLabel);
          }
        });
      });
    } catch (e) {
      console.log(e);
    }
  }

  return (
    <div className="map">
      <NavHeader
        title="地图找房"
        style={{ backgroundColor: "#f6f5f6" }}
        onBack={() => navigate(-1)}
      />
      <div id="container"></div>
    </div>
  );
}
